<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="800px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="140px"
      >
        <el-row :gutter="0">
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input
                class="data-input"
                v-model="form.contact"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="phone">
              <el-input
                class="data-input"
                v-model="form.phone"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="相关方类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio
                  v-for="(item, index) of dict['tenantType']"
                  :key="index"
                  :value="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="相关方名称" prop="name">
              <el-input
                class="data-input"
                v-model="form.name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
            v-if="
              ['企业', '政府'].includes(getDictValue('tenantType', form.type))
            "
          >
            <el-form-item
              label="统一社会信用代码"
              prop="code"
              :rules="rules.code1"
            >
              <el-input
                class="data-input"
                v-model="form.code"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            :span="12"
            v-if="['个人'].includes(getDictValue('tenantType', form.type))"
          >
            <el-form-item label="身份证号码" prop="code" :rules="rules.code2">
              <el-input
                class="data-input"
                v-model="form.code"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作业园区" prop="parkId">
              <el-select
                class="data-input"
                v-model="form.parkId"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) of parkOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.pkid"
                  :disabled="item.enable === '0'"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="施工类型" prop="workType">
              <el-select
                class="data-input"
                v-model="form.workType"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) of dict['construction_type']"
                  :key="index"
                  :label="item.name"
                  :value="item.pkid"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作业地点" prop="workLocation">
              <el-input
                class="data-input"
                v-model="form.workLocation"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="作业时间" prop="time">
              <el-date-picker
                v-model="form.time"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="事由">
              <el-input
                class="data-input"
                v-model="form.reason"
                placeholder="请输入"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="作业地点图片">
              <VUpload
                listType="picture-card"
                uploadText=""
                accept=".png, .jpg, .jepg"
                v-model="form.workLocationImg"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件资料">
              <VUpload width="250" v-model="form.files" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)" :loading="loading"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { cardId } from '@/utils/validate'
import { useDict } from '@/hooks/useDict'
const { dict, getDictValue } = useDict(['construction_type', 'tenantType'])
import VUpload from '@/components/upload/index.vue'
import {
  relatedAdd,
  relatedUpdate,
  relatedDetail,
} from '@/api/manager/dataManage/related'
import { parkPageList } from '@/api/manager/dataManage/park'
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  async () => {
    if (props.detail.pkid && dialogVisible.value) {
      handleDetail()
    } else {
      if (props.detail.parkId) {
        form.value.parkId = props.detail.parkId
      }
    }
  },
)
const handleDetail = async () => {
  const res = await relatedDetail({ pkid: props.detail.pkid })
  if (res.success) {
    // 处理时间
    res.data.time = [res.data.workStartTime, res.data.workEndTime]
    // 处理作业点的图片
    res.data.workLocationImg = res.data.imgFileList || []
    delete res.data.imgFileList
    // 处理附件资料
    res.data.files = res.data.fileList || []
    delete res.data.fileList
    form.value = { ...res.data }
  } else {
    ElMessage.error(res.message)
  }
}
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  form.value = { workLocationImg: [], time: [], files: [] }
  formRef.value.clearValidate()
  dialogVisible.value = false
  emit('close', isFlash)
}
const formRef = ref(null)
const form = ref({
  workLocationImg: [],
  time: [],
  files: [],
})
const validateIdCard = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const list = cardId(value)
    if (value && list[0]) {
      callback(new Error(list[1]))
    } else {
      callback()
    }
  }
}
const rules = ref({
  parkId: [{ required: true, message: '请选择所在园区', trigger: 'blur' }],
  type: [{ required: true, message: '请选择相关方类型', trigger: 'blur' }],
  name: [{ required: true, message: '请输入相关方主体名称', trigger: 'blur' }],
  code1: [
    {
      required: true,
      message: '请输入统一社会信用代码',
      trigger: 'blur',
    },
    {
      message: '请输入15或18位统一社会信用代码',
      pattern:
        /^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$/,
      trigger: 'blur',
    },
  ],
  code2: [
    {
      required: true,
      message: '请输入身份证号码',
      trigger: 'blur',
    },
    {
      validator: validateIdCard,
    },
  ],
  phone: [
    {
      pattern: /^1[34578]\d{9}$/,
      message: '请输入正确手机号',
      trigger: 'blur',
    },
  ],
  workType: [{ required: true, message: '请选择施工类型', trigger: 'blur' }],
  workLocation: [
    { required: true, message: '请输入作业地点', trigger: 'blur' },
  ],
  time: [{ required: true, message: '请选择作业时间', trigger: 'blur' }],
})

const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = JSON.parse(JSON.stringify(form.value))
      // 处理时间
      params.workStartTime = params.time[0]
      params.workEndTime = params.time[1]
      delete params.time
      // 处理作业地点图片
      if (params.workLocationImg && params.workLocationImg.length > 0) {
        params.workLocationImg = params.workLocationImg
          .map((i) => {
            return i.pkid
          })
          .join(',')
      } else {
        params.workLocationImg = ''
      }
      // 处理附件资料
      if (params.files && params.files.length > 0) {
        params.files = params.files
          .map((i) => {
            return i.pkid
          })
          .join(',')
      } else {
        params.files = ''
      }
      try {
        let res
        if (form.value.pkid) {
          res = await relatedUpdate(params)
        } else {
          res = await relatedAdd(params)
        }
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        console.log('error', error)
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const parkOptions = ref([])
const initParkList = async () => {
  const res = await parkPageList({ pageIndex: 1, pageSize: 9999 })
  parkOptions.value = res.data.list
}
defineExpose({ dialogVisible, title })
onMounted(() => {
  initParkList()
})
</script>
<style lang="scss" scoped></style>
